package mysql

import (
	"go.uber.org/zap"
	"personal-blog/models"
	"time"
)

// CreatePost 创建博客
func CreatePost(blog *models.Blog) (err error) {
	// 把博客插入数据库
	db.Table("blogs").Create(map[string]interface{}{
		"blog_id": blog.BlogID, "title": blog.Title, "author": blog.Author, "tags": blog.Tags, "short": blog.Short, "content": blog.Content, "create_time": time.Now(),
	})
	if err != nil {
		zap.L().Error("insert post failed", zap.Error(err))
		err = ErrorInsertFailed
		return
	}
	return
}

//得到用户列表
func GetUserDetailByUserName(NameStr string) (blog []models.Blog, err error) {
	db.Table("blogs").Select("blog_id", "title", "short").Where("author = ?", NameStr).Find(&blog)
	return blog, err
}

//得到博客详细信息
func GetBlogDetailByID(id int64) (blog *models.Blog, err error) {
	db.Table("blogs").Where("blog_id = ?", id).Find(&blog)

	return blog, err
}

// 查看所有的文章  并分页
func GetBlogList(page, size int) (posts []*models.Blog, err error) {
	db.Table("blogs").Limit(size).Offset((page - 1) * size).Find(&posts)
	return
}

//修改博客
func UpdateBlogDetailByID(id int64, blog *models.Blog) (err error) {
	db.Table("blogs").Where("blog_id = ?", id).Updates(map[string]interface{}{"title": blog.Title, "tags": blog.Tags, "short": blog.Short, "content": blog.Content, "create_time": time.Now()})
	return err
}

//删除博客
func DeleteBlogDetailByID(id int64) (err error) {
	db.Table("blogs").Where("blog_id = ?", id).Delete(id)
	return err
}
